package com.kapo.egroup.common;

import lombok.Data;

/**
 * 全局统一返回结果集
 *
 * @author starsea
 * @date 2022-07-13 11:07
 */
@Data
public class Result<T> {
    /**
     * 是否成功
     */
    private Boolean success;

    /**
     * 状态码
     */
    private Integer code;
    /**
     * 返回消息
     */
    private String message;
    /**
     * 返回数据
     */
    private T data;

    public Result() {
    }

    /**
     * 成功执行，未返回数据
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok() {
        return restResult(true,null, ResponseEnum.SUCCESS);
    }

    /**
     * 执行成功，并返回数据
     * @param data
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok(T data) {
        return restResult(true,data, ResponseEnum.SUCCESS);
    }

    /**
     * 执行失败
     * @param <T>
     * @return
     */
    public static <T> Result<T> fail() {
        return restResult(false,null, ResponseEnum.OPERATION_FAILED);
    }

    /**
     * 设置是否成功
     * @param success
     * @return
     */
    public Result<T> success(Boolean success) {
        this.setSuccess(success);
        return this;
    }

    /**
     * 设置响应枚举
     * @param msg
     * @return Result
     */
    public Result<T> msg(String msg) {
        this.setMessage(msg);
        return this;
    }

    /**
     * 设置响应枚举
     * @param responseEnum
     * @return
     */
    public Result<T> result(ResponseEnum responseEnum) {
        this.setCode(responseEnum.getCode());
        this.setMessage(responseEnum.getDesc());
        return this;
    }

    private static <T> Result<T> restResult(Boolean success, T data, ResponseEnum responseEnum) {
        Result<T> apiResult = new Result<>();
        apiResult.setSuccess(success);
        apiResult.setCode(responseEnum.getCode());
        apiResult.setData(data);
        apiResult.setMessage(responseEnum.getDesc());
        return apiResult;
    }
}
